package com.liser.material.design.ui.install;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.liser.material.design.R;
import com.liser.material.design.framework.helper.ToastHelper;
import com.liser.material.design.framework.observer.NothingObserver;
import com.liser.material.design.framework.observer.SimpleObserver;
import com.liser.material.design.framework.ui.BaseFragment;
import com.liser.material.design.hardware.BluetoothClientFactory;
import com.liser.material.design.hardware.ClassicBluetoothClient;
import com.liser.material.design.hardware.listener.ClassicBluetoothListener;
import com.liser.material.design.hardware.model.BluetoothDeviceDTO;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListSectionHeaderFooterView;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class InstallFragment extends BaseFragment {

    private static final String TAG = InstallFragment.class.getName();

    public static final int REQUEST_ENABLE_BT = 1229;

    @BindView(R.id.shfv_connected)
    QMUIGroupListSectionHeaderFooterView connectedSectionHeaderFooter;

    @BindView(R.id.qmui_cliv_connected)
    QMUICommonListItemView connectedCommonListItem;

    @BindView(R.id.shfv_searched)
    QMUIGroupListSectionHeaderFooterView searchedSectionHeaderFooter;

    @BindView(R.id.rv_searched)
    RecyclerView searchedRecyclerView;

    @BindView(R.id.bluetoothScan)
    Button bluetoothScan;

    private BluetoothAdapter bluetoothAdapter;

    private BluetoothClient bluetoothClient;

    private ClassicBluetoothClient classicBluetoothClient;

    private BluetoothItemAdapter searchedItemAdapter;

    private BluetoothItemAdapter.OnItemClickListener searchedClickListener;

    private ClassicBluetoothListener classicBluetoothListener;

    private CompoundButton.OnCheckedChangeListener connectedCheckedChangeListener;

    private Set<String> macSet = new HashSet<>(16);

    @Override
    protected int onLayout() {
        return R.layout.fragment_install;
    }

    @Override
    protected void onView() {
        classicBluetoothClient = BluetoothClientFactory.getClassicBluetoothClient();
        initBluetooth();
        initListener();
        initView();
        initRecyclerView(getContext());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                // 蓝牙已打开
            } else {
                // 蓝牙未打开
                ToastHelper.show(R.string.bluetooth_is_not_enabled);
            }
        }
    }

    @OnClick(R.id.bluetoothScan)
    public void onBluetoothScan(View view) {
        CharSequence scanText = bluetoothScan.getText();
        if ("扫描".contentEquals(scanText)) {
            searchBluetoothDevices();
        } else if ("停止".contentEquals(scanText)) {
            stopSearchBluetoothDevices();
        }
    }

    /**
     * 初始化蓝牙
     */
    private void initBluetooth() {
        bluetoothClient = BluetoothClientFactory.getBluetoothClient(getContext());
        checkBluetooth(bluetoothClient);
        bluetoothAdapter = BluetoothClientFactory.getBluetoothAdapter();
    }

    /**
     * 检查蓝牙状态
     */
    private void checkBluetooth(BluetoothClient bluetoothClient) {
        if (!bluetoothClient.isBleSupported()) {
            ToastHelper.show(R.string.phone_not_support_bluetooth);
        } else {
            if (!bluetoothClient.isBluetoothOpened()) {
                bluetoothClient.openBluetooth();
            }
        }
    }

    private void searchBluetoothDevices() {
        bluetoothClient.search(new SearchRequest.Builder()
                        .searchBluetoothClassicDevice(3000, 3) // 先扫经典蓝牙设备3次，每次3s
                        .searchBluetoothClassicDevice(2000) // 再扫BLE设备2s
                        .build()
                , new SearchResponse() {

                    @Override
                    public void onSearchStarted() {
                        bluetoothScan.setText("停止");
                    }

                    @Override
                    public void onDeviceFounded(SearchResult searchResult) {
                        boolean isNotDuplication = macSet.add(searchResult.getAddress());
                        if (isNotDuplication) {
                            BluetoothDeviceDTO bluetoothDeviceDTO = new BluetoothDeviceDTO(searchResult.getName(), searchResult.getAddress());
                            searchedItemAdapter.addBluetooth(bluetoothDeviceDTO);
                        }
                    }

                    @Override
                    public void onSearchStopped() {
                        bluetoothScan.setText("扫描");
                    }

                    @Override
                    public void onSearchCanceled() {
                        bluetoothScan.setText("扫描");
                        if (searchedItemAdapter.getItemCount() == 0) {
                            BluetoothDeviceDTO searchedDTO = new BluetoothDeviceDTO("未搜索到蓝牙", "");
                            searchedItemAdapter.addBluetooth(searchedDTO);
                        }
                    }
                });
    }

    private void stopSearchBluetoothDevices() {
        bluetoothClient.stopSearch();
    }

    private void initView() {
        connectedSectionHeaderFooter.setText(getResources().getString(R.string.connected_device));

        connectedCommonListItem.setOrientation(QMUICommonListItemView.VERTICAL);
        connectedCommonListItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_SWITCH);
        BluetoothDevice bluetoothDevice = classicBluetoothClient.getConnectedBluetoothDevice();
        if (bluetoothDevice != null) {
            macSet.add(bluetoothDevice.getAddress());
            connectedCommonListItem.setText(bluetoothDevice.getName());
            connectedCommonListItem.setDetailText(bluetoothDevice.getAddress());
            connectedCommonListItem.getSwitch().setChecked(true);
        } else {
            connectedCommonListItem.setText(getResources().getString(R.string.device_not_connected));
            connectedCommonListItem.setDetailText("");
        }

        connectedCommonListItem.getSwitch().setOnCheckedChangeListener(connectedCheckedChangeListener);
        connectedCommonListItem.setOnClickListener(view -> {
            // disable掉且不可点击，然后通过整个item的点击事件来toggle开关的状态
            connectedCommonListItem.getSwitch().toggle();
        });

        searchedSectionHeaderFooter.setText(getResources().getString(R.string.device_searched));
    }

    private void initRecyclerView(Context context) {
        VirtualLayoutManager searchedManager = new VirtualLayoutManager(context);
        LayoutHelper searchedHelper = new LinearLayoutHelper();
        searchedRecyclerView.setLayoutManager(searchedManager);
        // 分割线
        searchedRecyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        searchedItemAdapter = new BluetoothItemAdapter(context, searchedHelper);
        // 设置点击监听
        searchedItemAdapter.addOnClickListener(searchedClickListener);
        // 初始化数据
        searchedRecyclerView.setAdapter(searchedItemAdapter);

        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices.size() > 0) {
            for (BluetoothDevice device : bondedDevices) {
                addRecycleItem(device.getAddress(), device.getName());
            }
        }
    }

    private void initListener() {
        searchedClickListener = (view, postion) -> {
            // 连接状态
            if (view instanceof QMUICommonListItemView) {
                QMUICommonListItemView qmuiView = (QMUICommonListItemView) view;
                CharSequence address = qmuiView.getDetailText();
                // 设置Item样式
                qmuiView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
                qmuiView.addAccessoryCustomView(new QMUILoadingView(getContext()));

                Observable
                        .fromCallable(() -> {
                            classicBluetoothListener.setPostion(postion);
                            connectBluetooth(address.toString(), classicBluetoothListener);
                            return NothingObserver.DEFAULT_MESSAGE;
                        })
                        .compose(this.bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SimpleObserver<String>() {
                            @Override
                            public void onSuccess(String s) {
                                qmuiView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_NONE);
                                qmuiView.addAccessoryCustomView(new QMUILoadingView(getContext()));
                            }
                        });
            }
        };

        classicBluetoothListener = new ClassicBluetoothListener() {
            @Override
            public void onConnectStatusChanged(BluetoothDevice bluetoothDevice, int status, int postion) {
                Log.i(TAG, "蓝牙连接监听：" + bluetoothDevice.getName() + " " + bluetoothDevice.getAddress() + " " + status);
                switch (status) {
                    case BluetoothProfile.STATE_CONNECTED:
                        connectedSuccess(bluetoothDevice, postion);
                        ToastHelper.show("设备连接成功");
                        break;
                    case BluetoothProfile.STATE_DISCONNECTED:
                        ToastHelper.show("设备连接失败");
                        break;
                    default:
                        break;
                }
            }
        };

        connectedCheckedChangeListener = (compoundButton, checked) -> {
            if (!checked) {
                if (classicBluetoothClient != null) {
                    classicBluetoothClient.disconnect();
                    addRecycleItem(connectedCommonListItem.getDetailText().toString(), connectedCommonListItem.getText().toString());
                    connectedCommonListItem.setText(getResources().getString(R.string.device_not_connected));
                    connectedCommonListItem.setDetailText("");
                }
            }
        };
    }

    private void connectBluetooth(String mac, ClassicBluetoothListener classicBluetoothListener) {
        BluetoothDevice remoteDevice = BluetoothClientFactory.getRemoteDevice(mac);
        if (remoteDevice != null) {
            classicBluetoothClient.connect(remoteDevice, classicBluetoothListener);
        }
    }

    private void addRecycleItem(String mac, String name) {
        if (TextUtils.isEmpty(mac)) {
            return;
        }
        boolean notDuplication = macSet.add(mac);
        if (notDuplication) {
            searchedItemAdapter.addBluetooth(new BluetoothDeviceDTO(name, mac));
        }
    }

    private void connectedSuccess(BluetoothDevice bluetoothDevice, int postion) {
        macSet.remove(bluetoothDevice.getAddress());
        searchedItemAdapter.deleteBluetooth(postion);
        connectedCommonListItem.setText(bluetoothDevice.getName());
        connectedCommonListItem.setDetailText(bluetoothDevice.getAddress());
        connectedCommonListItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_SWITCH);
        connectedCommonListItem.getSwitch().setChecked(true);
    }

}